package cn.schoolwow.quickdao.domain.entity;

import java.io.*;
import java.lang.reflect.Field;

/**
 * 实体类属性信息
 */
public class Property extends PropertyOption implements Serializable, Cloneable {
    /**
     * 返回列标签名称
     */
    public String columnLabel;

    /**
     * 类
     */
    public transient Class clazz;

    /**
     * 类名
     */
    public String className;

    /**
     * 转义后的check约束
     */
    public String escapeCheck;

    /**
     * 是否为外键列
     */
    public transient boolean foreignKeyColumn;

    /**
     * 所属实体
     */
    public transient Entity entity;

    /**
     * 对应Java字段对象
     * */
    public transient Field field;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Property property = (Property) o;

        if (!column.equals(property.column)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return column.hashCode();
    }

    /**
     * 复制拷贝transient字段
     */
    public void copyTransientField(Property target) {
        this.strategy = target.strategy;
        this.clazz = target.clazz;
        this.foreignKey = target.foreignKey;
        this.entity = target.entity;
        this.field = target.field;
    }

    @Override
    public Property clone() {
        ByteArrayInputStream bais = null;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);
            oos.close();

            bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            Property property = (Property) ois.readObject();
            property.copyTransientField(this);
            bais.close();
            return property;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != bais) {
                try {
                    bais.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
